<template>
    <div id="scoresegment">
        <div class="title">一分一段</div>

        <el-card class="main">
            <!-- 标题 -->
            <div class="main_header">
                <div class="main_header_title">分数段列表</div>
                <div class="main_header_tool">
                    <el-button class="tool_btn" type="primary">批量导入</el-button>
                    <el-button class="tool_btn" type="primary" @click="addFormVisible = true">新增</el-button>
                </div>
            </div>

            <!-- 查询 -->
            <div class="main_query">
                <div class="main_query_form">
                    <el-form :inline="true" :model="queryForm" class="demo-form-inline" :rules="queryFormRules" ref="queryRuleFormRef" :show-message="false">
                        <el-row :gutter="24">
                            <el-col :span="6">
                                <el-form-item label="高考省份/直辖市：" prop="province">
                                    <el-input v-model="queryForm.province" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="年份：" prop="year">
                                    <el-input v-model="queryForm.year" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="报考科目类别：" prop="subject">
                                    <el-input v-model="queryForm.subject" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6" style="display:flex;">
                                <el-form-item label="分数段：" prop="Fmax" style="margin-right: 10px;">
                                    <el-input v-model="queryForm.Fmax" style="width:70px;" />
                                </el-form-item>
                                <el-form-item label="至" prop="Fmin">
                                    <el-input v-model="queryForm.Fmin" style="width:70px;" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="main_query_tool">
                    <el-button class="tool_btn" type="primary" @click="getQueryData(queryRuleFormRef)">查询</el-button>
                </div>
            </div>

            <!-- 数据显示 -->
            <el-table
                ref="multipleTableRef"
                :data="tableData"
                style="width: 100%;height: 520px;"
                @selection-change="handleSelectionChange"
                class="main_table"
            >
                <el-table-column type="selection" />
                <el-table-column property="fraction" label="分数" />
                <el-table-column property="province" label="高考省份/直辖市" />
                <el-table-column property="year" label="年份"  />
                <el-table-column property="subject" label="报考科目类别" />
                <el-table-column property="people" label="本段人数" />
                <el-table-column property="allPeople" label="累计人数" />
                <el-table-column label="操作" >
                    <template #default="scope">
                        <el-button class="tool_btn edit" type="primary" @click="handleredit(scope.row)">编辑</el-button>
                        <el-button class="tool_btn del" type="danger" @click="handlerdel(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 批量删除 -->
            <div class="allDel">
                <el-button text  @click="handlerAllDel">批量删除</el-button >
            </div>

            <!-- 分页 -->
            <el-pagination
                background
                v-model:current-page="params.pagenum"
                :page-size="params.pagesize"  
                layout="prev, pager, next" 
                @current-change="handleCurrentChange"
                :total="total"
            />
        </el-card>

         <!-- 新增对话框 -->
        <el-dialog title="批次线新增" v-model="addFormVisible" width="40%" center @close="addResetForm(addRuleFormRef)">
            <el-form :model="addform" :rules="addFormRules" ref="addRuleFormRef" :hide-required-asterisk="true">
                <el-form-item label="高考省份/直辖市：" label-width="140px" prop="province">
                    <el-input v-model.trim="addform.province" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="年份：" label-width="140px" prop="year">
                    <el-input v-model.number="addform.year" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="报考科目类别：" label-width="140px" prop="subject">
                    <el-input v-model.trim="addform.subject" style="width: 120px;"  />
                </el-form-item>
                <el-form-item label="分数：" label-width="140px" prop="fraction">
                    <el-input v-model.number="addform.fraction" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="本段人数：" label-width="140px" prop="people">
                    <el-input v-model.number="addform.people" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="积累人数：" label-width="140px" prop="allPeople">
                    <el-input v-model.number="addform.allPeople" style="width: 120px;" />
                </el-form-item>
            </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="addResetForm(addRuleFormRef)">取消</el-button>
                <el-button type="primary"  @click="addSubmitForm(addRuleFormRef)">提交</el-button>
            </span>
            </template>
        </el-dialog>

        <!-- 修改对话框 -->
        <el-dialog title="批次线编辑" v-model="editFormVisible" width="40%" center @close="editResetForm(editRuleFormRef)">
            <el-form :model="editform" :rules="editFormRules" ref="editRuleFormRef" :hide-required-asterisk="true">
                <el-form-item label="高考省份/直辖市：" label-width="140px" prop="province">
                    <el-input v-model.trim="editform.province" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="年份：" label-width="140px" prop="year">
                    <el-input v-model.number="editform.year" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="报考科目类别：" label-width="140px" prop="subject">
                    <el-input v-model.trim="editform.subject" style="width: 120px;"  />
                </el-form-item>
                <el-form-item label="分数：" label-width="140px" prop="fraction">
                    <el-input v-model.number="editform.fraction" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="本段人数：" label-width="140px" prop="people">
                    <el-input v-model.number="editform.people" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="积累人数：" label-width="140px" prop="allPeople">
                    <el-input v-model.number="editform.allPeople" style="width: 120px;" />
                </el-form-item>
            </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="editResetForm(editRuleFormRef)">取消</el-button>
                <el-button type="primary"  @click="editSubmitForm(editRuleFormRef,getAllData)">提交</el-button>
            </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { reactive, toRefs, ref } from '@vue/reactivity'
import { fractionAll, fractionQuery, fractionAdd, fractionModify, fractionDel } from '../api/axiosPlus'

// 获取数据
function useGetData () {
    const provincePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入查询参数'))
        } else {
            callback()
        }
    }
    const yearPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入查询参数'))
        } else {
            callback()
        }
    }
    const subjectPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入查询参数'))
        } else {
            callback()
        }
    }
    const FmaxPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入查询参数'))
        } else {
            callback()
        }
    }
    const FminPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入查询参数'))
        } else {
            callback()
        }
    }
    const queryRuleFormRef = ref()

    let data = reactive({
        tableData: [],
        queryData: [],
        queryForm: {
            province: '',
            year: '',
            subject: '',
            Fmax: '',
            Fmin: ''
        },
        queryFormRules: {
            province: [{ validator: provincePass, trigger: 'blur' }],
            year: [{ validator: yearPass, trigger: 'blur' }],
            subject: [{ validator: subjectPass, trigger: 'blur' }],
            Fmax: [{ validator: FmaxPass, trigger: 'blur' }],
            Fmin: [{ validator: FminPass, trigger: 'blur' }]
        },
        params: {
            pagenum: 1,
			pagesize: 4
        },
        total: 0
    })

    
    // 请求所有数据
    const getAllData = async (flag) => {
        // onMounted(async () => {
            if(flag) {
                data.params.pagenum = 1
            }
            console.log(data.params)
            const res = await fractionAll({
                params: data.params
            })
        
            console.log(res);
            if(res.status !== 200) return console.log('获取所有数据失败')
            data.tableData = res.result
            data.total = res.total
            console.log('所有数据：',res.result);
        // })
    }

    // 查询获取数据
    const getQueryData = (queryRuleFormRef) => {
        console.log(data.queryForm);
        if (!queryRuleFormRef) return

        queryRuleFormRef.validate(async (valid,val) => {
            console.log(val);
            if (valid) {
                console.log('submit!')
                // 查询
                const res = await fractionQuery(data.queryForm)
                queryRuleFormRef.resetFields() // 清除表单

                if(res.status !== 200) return ElMessage({
                    message: '查询失败！',
                    type: 'warning',
                    duration: 2000
                })

                if (res.data.length === 0) {
                        ElMessage({
                            message: '没有查找到相关数据！',
                            type: 'warning',
                            duration: 2000
                        })
                        getAllData(true)
                        return
                    }

                data.tableData = res.data
                data.total = res.data.length
            } else {
                console.log('error submit!')
                console.log(Object.getOwnPropertyNames(val).length) // Object.getOwnPropertyNames获取对象可枚举或不可枚举的属性 返回数组，数组元素为对象属性名
                
                if (Object.getOwnPropertyNames(val).length === 5) {
                    setTimeout(()=>{
                        queryRuleFormRef.resetFields()
                    },2000)
                    ElMessage({
                        message: '至少需要一个查询参数',
                        type: 'warning',
                        duration: 2000
                    })
                    getAllData(true)
                    return 
                } else {
                    // 查询
                    const res = await fractionQuery(data.queryForm)
                    queryRuleFormRef.resetFields() // 清除表单

                    if(res.status !== 200) return ElMessage({
                        message: '查询失败！',
                        type: 'warning',
                        duration: 2000
                    })

                    if (res.data.length === 0) {
                        ElMessage({
                            message: '没有查找到相关数据！',
                            type: 'warning',
                            duration: 2000
                        })
                        getAllData(true)
                        return
                    }

                    data.tableData = res.data
                    data.total = res.data.length
                    console.log(res,data.tableData);
                }
                
                return false
            }
        })
    }

    // 分页
    const handleCurrentChange = (val) => {
        data.params.pagenum = val
        console.log(data.params);
        getAllData()
    }

    return {
        queryRuleFormRef,
        ...toRefs(data),
        getAllData,
        getQueryData,
        handleCurrentChange
    }
}

// 新增数据
function useAddData (callback) {
    // 新增对话框  对话框显示状态 添加表单
    const provincePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入省份/直辖市'))
        } else {
            callback()
        }
    }
    const yearPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入年份'))
        } else {
            callback()
        }
    }
    const subjectPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入报考科目类别'))
        } else {
            callback()
        }
    }
    const fractionPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入分数'))
        } else {
            callback()
        }
    }
    const peoplePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入本段人数'))
        } else {
            callback()
        }
    }
    const allPeoplePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入积累人数'))
        } else {
            callback()
        }
    }
    const addRuleFormRef = ref()
    const addFormVisible = ref(false)
    const addformData = reactive({
        addform: {
            province: "",
            year: '',
            subject: "",
            fraction: '',
            people: '',
            allPeople: ''
        },
        addFormRules: {
            province: [{ validator: provincePass, trigger: 'blur' }],
            year: [{ validator: yearPass, trigger: 'blur' }],
            subject: [{ validator: subjectPass, trigger: 'blur' }],
            fraction: [{ type: 'number', message: '请输入数字' },{ validator: fractionPass, trigger: 'blur' }],
            people: [{ type: 'number', message: '请输入数字' },{ validator: peoplePass, trigger: 'blur' }],
            allPeople: [{ type: 'number', message: '请输入数字' },{ validator: allPeoplePass, trigger: 'blur' }]
        },
    })

    // 提交按钮
    const addSubmitForm = (addRuleFormRef) => {
        if (!addRuleFormRef) return
        addRuleFormRef.validate(async (valid) => {
            if (valid) {
                console.log(addformData.addform)
                const res = await fractionAdd(addformData.addform)
                console.log(res);
                addRuleFormRef.resetFields()
                addFormVisible.value = false
                ElMessage({
                    message: '添加成功！',
                    type: 'success',
                    duration: 2000
                })
                callback(true)
            } else {
                console.log('error submit!')
                return false
            }
        })
    }

    // 取消提交
    const addResetForm = (formEl) => {
        if (!formEl) return
        formEl.resetFields()
        addFormVisible.value = false
    }

    return {
        addFormVisible,
        addRuleFormRef,
        ...toRefs(addformData),
        addSubmitForm,
        addResetForm
    }
}

// 编辑数据
function useEditData () {
    // 编辑对话框  对话框显示状态 编辑表单
    const provincePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入省份/直辖市'))
        } else {
            callback()
        }
    }
    const yearPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入年份'))
        } else {
            callback()
        }
    }
    const subjectPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入报考科目'))
        } else {
            callback()
        }
    }
    const fractionPass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入分数'))
        } else {
            callback()
        }
    }
    const peoplePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入本段人数'))
        } else {
            callback()
        }
    }
    const allPeoplePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入积累人数'))
        } else {
            callback()
        }
    }
    const editRuleFormRef = ref()
    const editFormVisible = ref(false)
    const editformData = reactive({
        editform: {
            province: "",
            year: '',
            subject: "",
            fraction: '',
            people: '',
            allPeople: ''
        },
        isSubmitform: {
            province: "",
            year: '',
            subject: "",
            fraction: '',
            people: '',
            allPeople: ''
        },
        editFormRules: {
            province: [{ validator: provincePass, trigger: 'blur' }],
            year: [{ validator: yearPass, trigger: 'blur' }],
            subject: [{ validator: subjectPass, trigger: 'blur' }],
            fraction: [{ type: 'number', message: '请输入数字' },{ validator: fractionPass, trigger: 'blur' }],
            people: [{ type: 'number', message: '请输入数字' },{ validator: peoplePass, trigger: 'blur' }],
            allPeople: [{ type: 'number', message: '请输入数字' },{ validator: allPeoplePass, trigger: 'blur' }]
        },
    })

    // 编辑
    const handleredit = (item) => {
        editFormVisible.value = true
        editformData.editform = JSON.parse(JSON.stringify(item))
        editformData.isSubmitform = JSON.parse(JSON.stringify(item))
        console.log(item)
    }

    // 提交按钮
    const editSubmitForm = (editRuleFormRef,callback) => {
        if (!editRuleFormRef) return
        editRuleFormRef.validate(async (valid) => {
            if (valid) {
                // console.log(JSON.stringify(editformData.editform) == JSON.stringify(editformData.isSubmitform))
                if (JSON.stringify(editformData.editform) == JSON.stringify(editformData.isSubmitform)) {
                    ElMessage({
                        message: '请修改信息！',
                        type: 'warning',
                        duration: 2000
                    })
                } else {
                    console.log(editformData.editform);
                    const res = await fractionModify({
                        id: editformData.editform.dt_id,
                        province: editformData.editform.province,
                        year: editformData.editform.year,
                        subject: editformData.editform.subject,
                        fraction: editformData.editform.fraction,
                        people: editformData.editform.people,
                        allPeople: editformData.editform.allPeople
                    })
                    console.log(res);
                    editFormVisible.value = false
                    ElMessage({
                        message: '修改成功！',
                        type: 'success',
                        duration: 2000
                    })
                    callback(true)
                }
                
            } else {
                console.log('error submit!')
                editFormVisible.value = false
                return false
            }
        })
    }

    // 取消提交
    const editResetForm = (formEl) => {
        if (!formEl) return
        formEl.resetFields()
        editFormVisible.value = false
    }

    return {
        editFormVisible,
        editRuleFormRef,
        ...toRefs(editformData),
        handleredit,
        editSubmitForm,
        editResetForm
    }
}

// 删除数据
function useDelData (callback) {
    let strId = ''
    const delInfo = reactive({
        tableSelection: []
    })

    // 单个删除
    const handlerdel = async (item) => {
        console.log('handlerdel',item);
        strId = item.dt_id
        console.log(strId);

        // 删除请求
        const res = await fractionDel({
            params: {
                id:strId
            }
        })
        if(res.status !== 201){ 
            ElMessage({
                message: '删除失败！',
                type: 'error',
                duration: 2000
            })
        } else {
            ElMessage({
                message: '删除成功！',
                type: 'success',
                duration: 2000
            })
            callback(true)
        }
    }

    // 多个删除
    const handlerAllDel = async () => {
        console.log(strId);
        // 删除请求
        const res = await fractionDel({id:strId})
        if(res.status !== 201){ 
            ElMessage({
                message: '批量删除失败！',
                type: 'error',
                duration: 2000
            })
        } else {
            ElMessage({
                message: '批量删除成功！',
                type: 'success',
                duration: 2000
            })
            callback(true)
        }
    }

    // 获取table选中数据
    const handleSelectionChange = (val) => {
        delInfo.tableSelection = val
        console.log(delInfo.tableSelection)

        const arr = JSON.parse(JSON.stringify(delInfo.tableSelection))
        const arrId = arr.map(v => v.dt_id)
        strId = arrId.join(",")
    }

    return {
        ...toRefs(delInfo),
        handleSelectionChange,
        handlerdel,
        handlerAllDel
    }
}

export default {
    setup() {
        // 渲染数据
        const { queryRuleFormRef, tableData, queryForm, queryFormRules, params, total, getAllData, getQueryData, handleCurrentChange } = useGetData() 
        // 新增
        const { addFormVisible, addform, addFormRules, addRuleFormRef, addSubmitForm, addResetForm } = useAddData()  
        // 编辑
        const { editFormVisible, editform, editFormRules, editRuleFormRef, handleredit, editSubmitForm, editResetForm } = useEditData()  
        // 删除
        const { tableSelection, handleSelectionChange, handlerdel, handlerAllDel } = useDelData(getAllData)


        getAllData()

        return {
            // 数据显示
            queryForm,
            params, 
            total,
            tableData,
            queryRuleFormRef,
            queryFormRules,
            getAllData,
            getQueryData,
            handleCurrentChange,

            //  新增对话框
            addform,
            addFormVisible, 
            addFormRules,
            addRuleFormRef,
            addSubmitForm,
            addResetForm,

            //  编辑对话框
            editform,
            editFormVisible, 
            editFormRules,
            editRuleFormRef,
            handleredit,
            editSubmitForm,
            editResetForm,

            // 删除
            tableSelection,
            handleSelectionChange,
            handlerdel,
            handlerAllDel
        }
    },
}
</script>

<style lang="less" scoped>
#scoresegment {
    .title {
        font-size: 17px;
        color: #101010;
        text-align: left;
        letter-spacing: 1px;
        margin-bottom: 20px;
    }

    .main {
    // 标题
        .main_header {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .main_header_title {
                color: #009EFF;
                font-size: 16px;
                padding: 0 2px 5px 2px;
                border-bottom: 2px solid #009EFF;
            }
            .main_header_tool {
                font-size: 14px;

                .tool_btn {
                    width: 120px;
                    background: #1EB96B;
                    border-color: #1EB96B;
                }
            }
        }

    // 查询
        .main_query {
            display: flex;
            justify-content: space-between;
            margin: 40px 0;

            .main_query_form {
                flex-grow: 1;
            }

            .main_query_tool {

                .tool_btn {
                    width: 80px;
                    background: #27B148;
                    border-color: #27B148;
                }
            }
        }

    // 数据显示
        .main_table {
            .tool_btn {
                height: 28px;
                width: 65px;
            }
        }

        .allDel {
            width: 100%;
            display: flex;
            justify-content: flex-start;
            margin-top: 20px;
        }
    }
}

/deep/.el-button {
    >span {
        font-size: 14px;
    }
}

/deep/.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf,
/deep/.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf {
    text-align: center;
}

/deep/.el-table th.el-table__cell.is-leaf{
    text-align: center;
    background: #E6F1FF;
}

/deep/.el-pagination.is-background .btn-next, 
/deep/.el-pagination.is-background .btn-prev, 
/deep/.el-pagination.is-background .el-pager .number{
    border: 1px solid #E8E8E8;
    background: #fff;
}

/deep/.el-pagination{
    justify-content: center;
}

/deep/.el-pagination.is-background .el-pager li:not(.is-disabled).is-active{
    background: #fff;
    color: #4C555D;
    font-weight: 500;
    border: 1px solid #1684FC;
}

/deep/.el-pager li.btn-quicknext, 
/deep/.el-pager li.btn-quickprev {
    border: 1px solid #E8E8E8;
    background: #fff;
}
</style>